package com.wjl.picture.picture.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wjl.picture.auth.SpaceUserAuthManager;
import com.wjl.picture.common.base.BaseResponse;
import com.wjl.picture.common.base.BatchDeleteRequest;
import com.wjl.picture.common.base.ResultUtils;
import com.wjl.picture.common.context.UserContext;
import com.wjl.picture.common.exception.BusinessException;
import com.wjl.picture.common.exception.ErrorCode;
import com.wjl.picture.common.exception.ThrowUtils;
import com.wjl.picture.picture.model.entity.Space;
import com.wjl.picture.picture.model.enums.SpaceLevelEnum;
import com.wjl.picture.picture.model.enums.SpaceTypeEnum;
import com.wjl.picture.picture.model.request.SpaceAddRequest;
import com.wjl.picture.picture.model.request.SpaceEditRequest;
import com.wjl.picture.picture.model.request.SpaceQueryRequest;
import com.wjl.picture.picture.model.request.SpaceUpdateRequest;
import com.wjl.picture.picture.model.vo.SpaceLevel;
import com.wjl.picture.picture.model.vo.SpaceVO;
import com.wjl.picture.picture.service.SpaceService;
import com.wjl.picture.user.model.constant.UserConstant;
import com.wjl.picture.user.model.entity.User;
import com.wjl.picture.user.model.enums.UserRoleEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 帖子接口
 */
@RestController
@RequestMapping("/space")
@Slf4j
public class SpaceController {

    @Resource
    private SpaceService spaceService;

    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;


    // region 增删改查

    /**
     * 创建
     *
     * @param spaceAddRequest
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addSpace(@RequestBody SpaceAddRequest spaceAddRequest) {
        long l = spaceService.addSpace(spaceAddRequest);
        return ResultUtils.success(l);
    }

    /**
     * 删除
     *
     * @param batchDeleteRequest
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteSpace(@RequestBody BatchDeleteRequest batchDeleteRequest) {
        User user = UserContext.getUser();
        spaceService.validDelete(batchDeleteRequest.getIds(), user);
        boolean b = spaceService.removeBatchByIds(batchDeleteRequest.getIds());
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param spaceUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @SaCheckRole(UserConstant.USER_ROLE_ADMIN)
    public BaseResponse<Boolean> updateSpace(@RequestBody SpaceUpdateRequest spaceUpdateRequest) {
        Space space = new Space();
        BeanUtils.copyProperties(spaceUpdateRequest, space);
        spaceService.fillSpaceBySpaceLevel(space);
        // 参数校验
        spaceService.validSpace(space, false);
        long id = spaceUpdateRequest.getId();
        // 判断是否存在
        Space oldSpace = spaceService.getById(id);
        ThrowUtils.throwIf(oldSpace == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = spaceService.updateById(space);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<SpaceVO> getSpaceVOById(long id) {
        Space space = spaceService.getById(id);
        if (space == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        SpaceVO spaceVO = spaceService.getSpaceVO(space);
        spaceVO.setPermissionList(spaceUserAuthManager.getPermissionList(space));
        return ResultUtils.success(spaceVO);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param spaceQueryRequest
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<SpaceVO>> listSpaceVOByPage(@RequestBody SpaceQueryRequest spaceQueryRequest) {
        long size = spaceQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<SpaceVO> spaceVOPage = spaceService.listSpaceVOByPage(spaceQueryRequest);
        return ResultUtils.success(spaceVOPage);
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param spaceQueryRequest
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<SpaceVO>> listMySpaceVOByPage(@RequestBody SpaceQueryRequest spaceQueryRequest) {
        User loginUser = UserContext.getUser();
        spaceQueryRequest.setUserId(loginUser.getId());
        long current = spaceQueryRequest.getCurrent();
        long size = spaceQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Space> spacePage = spaceService.page(new Page<>(current, size),
                spaceService.getLambdaQueryWrapper(spaceQueryRequest));
        return ResultUtils.success(spaceService.getSpaceVOPage(spacePage));
    }

    // endregion

    /**
     * 编辑（用户）
     *
     * @param spaceEditRequest
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editSpace(@RequestBody SpaceEditRequest spaceEditRequest) {
        Space space = new Space();
        BeanUtils.copyProperties(spaceEditRequest, space);
        // 参数校验
        spaceService.validSpace(space, false);
        User loginUser = UserContext.getUser();
        long id = spaceEditRequest.getId();
        // 判断是否存在
        Space oldSpace = spaceService.getById(id);
        ThrowUtils.throwIf(oldSpace == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldSpace.getUserId().equals(loginUser.getId()) && !UserRoleEnum.ROLE_ADMIN.getValue().equals(loginUser.getUserRole())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = spaceService.updateById(space);
        return ResultUtils.success(result);
    }

    @GetMapping("/list/level")
    public BaseResponse<List<SpaceLevel>> listSpaceLevel() {
        List<SpaceLevel> spaceLevelList = Arrays.stream(SpaceLevelEnum.values()) // 获取所有枚举
                .map(spaceLevelEnum -> new SpaceLevel(
                        spaceLevelEnum.getValue(),
                        spaceLevelEnum.getText(),
                        spaceLevelEnum.getMaxCount(),
                        spaceLevelEnum.getMaxSize()))
                .collect(Collectors.toList());
        return ResultUtils.success(spaceLevelList);
    }

    /**
     * 查询我加入的团队空间列表
     */
    @PostMapping("/get/my/team")
    public BaseResponse<SpaceVO> getMyTeamSpace() {
        User loginUser = UserContext.getUser();
        SpaceQueryRequest queryRequest = new SpaceQueryRequest();
        queryRequest.setUserId(loginUser.getId());
        queryRequest.setSpaceType(SpaceTypeEnum.TEAM.getValue());
        List<Space> spaceList = spaceService.list(
                spaceService.getLambdaQueryWrapper(queryRequest)
        );
        SpaceVO spaceVO=null;
        if (CollUtil.isNotEmpty(spaceList)) {
            spaceVO=spaceService.getSpaceVO(spaceList.get(0));
            spaceVO.setPermissionList(spaceUserAuthManager.getPermissionList(spaceList.get(0)));
        }
        return ResultUtils.success(spaceVO);
    }
}
